package com.fanketly.module_safe_photo.data.repo

import androidx.room.Room
import com.blankj.utilcode.util.LogUtils
import com.fanketly.module_safe_photo.data.SafeDatabase
import com.fanketly.module_safe_photo.data.SafePhotoSortDao
import com.fanketly.module_safe_photo.data.SafePhotoUrlDao
import com.fanketly.module_safe_photo.data.model.SafePhotoModel
import com.fanketly.module_safe_photo.data.model.SafePhotoSortModel
import fanketly.core.CoreApp
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext

/**
 *Create by Fanketly on 2022/7/15
 *Modified 2022/8/18
 *Gitee:https://gitee.com/fanketly
 *desc:
 */
class SafePhotoRepo {
    private val build =
        Room.databaseBuilder(CoreApp.context, SafeDatabase::class.java, "safe_photo_db")
            .enableMultiInstanceInvalidation().build()
    private val safeUrlDao: SafePhotoUrlDao by lazy { build.safeUrlDao() }
    private val safePhotoSortDao: SafePhotoSortDao by lazy { build.safePhotoSortDao() }


    suspend fun getPhotoBySortPosition(sortPosition:Int): List<SafePhotoModel> =
        withContext(Dispatchers.IO) { safeUrlDao.getBySortPosition(sortPosition) }

    suspend fun addPhoto(safeUrlModel: SafePhotoModel) =
        withContext(Dispatchers.IO) { safeUrlDao.insert(safeUrlModel) }

    suspend fun updatePhoto(safeUrlModel: SafePhotoModel): Int =
        withContext(Dispatchers.IO) {
            safeUrlDao.update(safeUrlModel)
        }

    suspend fun deletePhoto(safeUrlModel: SafePhotoModel): Int =
        withContext(Dispatchers.IO) {
            safeUrlDao.delete(safeUrlModel)
        }

    ///////////////////////////////////////////////////////////////////////////
    //
    ///////////////////////////////////////////////////////////////////////////
    suspend fun getAllPhotoSort(): List<SafePhotoSortModel> =
        withContext(Dispatchers.IO) { safePhotoSortDao.getAll() }

    suspend fun addPhotoSort(safePhotoSortModel: SafePhotoSortModel) =
        withContext(Dispatchers.IO) { safePhotoSortDao.insert(safePhotoSortModel) }

    suspend fun updatePhotoSort(safePhotoSortModel: SafePhotoSortModel): Int =
        withContext(Dispatchers.IO) {
            safePhotoSortDao.update(safePhotoSortModel)
        }

    suspend fun deletePhotoSort(safePhotoSortModel: SafePhotoSortModel): Int =
        withContext(Dispatchers.IO) {
            safePhotoSortDao.delete(safePhotoSortModel)
        }
}